import { NativeModules, Dimensions } from 'react-native';
import { SCROLL_SPEEDS, PERFORMANCE_CONFIG } from '../utils/constants';
import { adjustCoordinatesForAds, safeExecute, sleepWithCancel, isPerformanceExceeded } from '../utils/helpers';

class AutoScrollService {
  constructor() {
    this.isScrolling = false;
    this.isPaused = false;
    this.scrollInterval = null;
    this.currentPlatform = null;
    this.settings = {
      interval: 10000,
      speed: 'medium',
      direction: 'vertical'
    };
    this.startTime = null;
    this.totalScrolls = 0;
    this.shouldStop = false;
  }

  /**
   * 开始自动滑动
   */
  async startAutoScroll(platform, settings, onScrollCallback) {
    if (this.isScrolling && !this.isPaused) {
      console.log('自动滑动已在运行中');
      return false;
    }

    this.currentPlatform = platform;
    this.settings = { ...this.settings, ...settings };
    this.isScrolling = true;
    this.isPaused = false;
    this.shouldStop = false;
    this.startTime = Date.now();
    this.totalScrolls = 0;

    console.log(`开始自动滑动 - 平台: ${platform}, 设置:`, this.settings);

    try {
      await this.scheduleNextScroll(onScrollCallback);
      return true;
    } catch (error) {
      console.error('启动自动滑动失败:', error);
      this.stopAutoScroll();
      return false;
    }
  }

  /**
   * 停止自动滑动
   */
  stopAutoScroll() {
    console.log('停止自动滑动');
    
    this.isScrolling = false;
    this.isPaused = false;
    this.shouldStop = true;
    
    if (this.scrollInterval) {
      clearTimeout(this.scrollInterval);
      this.scrollInterval = null;
    }

    this.currentPlatform = null;
    this.startTime = null;
    this.totalScrolls = 0;
  }

  /**
   * 暂停自动滑动
   */
  pauseAutoScroll() {
    if (!this.isScrolling || this.isPaused) return;
    
    console.log('暂停自动滑动');
    this.isPaused = true;
    
    if (this.scrollInterval) {
      clearTimeout(this.scrollInterval);
      this.scrollInterval = null;
    }
  }

  /**
   * 恢复自动滑动
   */
  async resumeAutoScroll(onScrollCallback) {
    if (!this.isScrolling || !this.isPaused) return;
    
    console.log('恢复自动滑动');
    this.isPaused = false;
    
    try {
      await this.scheduleNextScroll(onScrollCallback);
    } catch (error) {
      console.error('恢复自动滑动失败:', error);
      this.stopAutoScroll();
    }
  }

  /**
   * 调度下一次滑动
   */
  async scheduleNextScroll(onScrollCallback) {
    if (!this.isScrolling || this.isPaused || this.shouldStop) return;

    // 性能检查
    if (isPerformanceExceeded()) {
      console.warn('性能超标，暂停滑动');
      this.pauseAutoScroll();
      return;
    }

    const interval = this.settings.interval || 10000;
    
    this.scrollInterval = setTimeout(async () => {
      if (this.shouldStop) return;
      
      try {
        const success = await this.performScroll(onScrollCallback);
        if (success) {
          this.totalScrolls++;
          if (onScrollCallback) {
            onScrollCallback({
              success: true,
              scrollCount: this.totalScrolls,
              platform: this.currentPlatform
            });
          }
        }
        
        // 递归调度下一次滑动
        if (!this.shouldStop) {
          await this.scheduleNextScroll(onScrollCallback);
        }
      } catch (error) {
        console.error('滑动执行失败:', error);
        if (onScrollCallback) {
          onScrollCallback({
            success: false,
            error: error.message,
            platform: this.currentPlatform
          });
        }
      }
    }, interval);
  }

  /**
   * 执行滑动操作
   */
  async performScroll(onScrollCallback) {
    try {
      const coordinates = this.getScrollCoordinates();
      const duration = this.getScrollDuration();
      
      console.log(`执行滑动 - 坐标:`, coordinates, `持续时间: ${duration}ms`);
      
      // 调用原生模块执行滑动
      const result = await this.simulateScroll(coordinates, duration);
      
      if (result) {
        console.log('滑动执行成功');
        return true;
      } else {
        console.warn('滑动执行失败');
        return false;
      }
    } catch (error) {
      console.error('滑动操作失败:', error);
      throw error;
    }
  }

  /**
   * 获取滑动坐标
   */
  getScrollCoordinates() {
    if (!this.currentPlatform) {
      throw new Error('未设置当前平台');
    }

    const { width, height } = Dimensions.get('window');
    const platformConfig = this.getPlatformConfig(this.currentPlatform);
    
    let coordinates = {
      startX: width * platformConfig.startXRatio,
      startY: height * platformConfig.startYRatio,
      endX: width * platformConfig.endXRatio,
      endY: height * platformConfig.endYRatio
    };

    // 广告区域避让
    if (platformConfig.adAvoidRegions && platformConfig.adAvoidRegions.length > 0) {
      coordinates = adjustCoordinatesForAds(coordinates, platformConfig.adAvoidRegions, { width, height });
    }

    return coordinates;
  }

  /**
   * 获取滑动持续时间
   */
  getScrollDuration() {
    const speedConfig = SCROLL_SPEEDS[this.settings.speed];
    return speedConfig ? speedConfig.duration : SCROLL_SPEEDS.medium.duration;
  }

  /**
   * 获取平台配置
   */
  getPlatformConfig(platform) {
    // 这里应该从platformAdapter获取，暂时直接返回基础配置
    const configs = {
      douyin: {
        startXRatio: 0.5,
        startYRatio: 0.8,
        endXRatio: 0.5,
        endYRatio: 0.2,
        adAvoidRegions: [
          { x: 0, y: 0, width: 1, height: 0.15 },
          { x: 0, y: 0.85, width: 1, height: 0.15 }
        ]
      },
      kuaishou: {
        startXRatio: 0.5,
        startYRatio: 0.8,
        endXRatio: 0.5,
        endYRatio: 0.2,
        adAvoidRegions: []
      },
      bilibili: {
        startXRatio: 0.8,
        startYRatio: 0.5,
        endXRatio: 0.2,
        endYRatio: 0.5,
        adAvoidRegions: []
      },
      local: {
        startXRatio: 0.5,
        startYRatio: 0.8,
        endXRatio: 0.5,
        endYRatio: 0.2,
        adAvoidRegions: []
      }
    };

    return configs[platform] || configs.douyin;
  }

  /**
   * 模拟滑动（调用原生模块）
   */
  async simulateScroll(coordinates, duration) {
    if (!NativeModules.ScrollSimulator) {
      console.warn('ScrollSimulator原生模块未找到，使用模拟模式');
      // 模拟滑动效果
      await safeExecute(async () => {
        await sleepWithCancel(duration, () => this.shouldStop);
      }, '模拟滑动');
      return true;
    }

    try {
      return await NativeModules.ScrollSimulator.simulateScroll(coordinates, duration);
    } catch (error) {
      console.error('原生滑动失败:', error);
      throw error;
    }
  }

  /**
   * 获取当前状态
   */
  getStatus() {
    return {
      isScrolling: this.isScrolling,
      isPaused: this.isPaused,
      currentPlatform: this.currentPlatform,
      settings: this.settings,
      totalScrolls: this.totalScrolls,
      startTime: this.startTime,
      elapsedTime: this.startTime ? Date.now() - this.startTime : 0
    };
  }

  /**
   * 执行单次滑动（手动触发）
   */
  async performSingleScroll(platform, direction = 'next') {
    const originalPlatform = this.currentPlatform;
    const originalSettings = { ...this.settings };
    
    try {
      this.currentPlatform = platform;
      this.settings.interval = 0; // 立即执行
      
      const coordinates = this.getScrollCoordinates();
      
      // 根据方向调整坐标
      if (direction === 'previous') {
        coordinates.startY = coordinates.endY;
        coordinates.endY = coordinates.startY + (coordinates.startY - coordinates.endY);
      }
      
      const duration = this.getScrollDuration();
      const result = await this.simulateScroll(coordinates, duration);
      
      return result;
    } catch (error) {
      console.error('单次滑动失败:', error);
      throw error;
    } finally {
      // 恢复原设置
      this.currentPlatform = originalPlatform;
      this.settings = originalSettings;
    }
  }
}

// 创建单例实例
const autoScrollService = new AutoScrollService();

export default autoScrollService;